﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using FastReflectionLib;
using HF.Repository.MSSql;

namespace HF.Repository
{
    public static class RepositoryModelExtension
    {
        /// <summary>
        /// 取得主键值
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static object GetKeyValue(this ReadonlyRepositoryModel model)
        {
            return RepositoryReflectionCache.GetKeyValue(model.GetType(), model);
        }

        /// <summary>
        /// 取得所有属性值的字符串，供更新之用
        /// </summary>
        /// <param name="model"></param>
        /// <returns>(val1,val2)</returns>
        public static string GetValueSting(this ReadonlyRepositoryModel model)
        {
            return model.GetValueSting(null);
        }

        /// <summary>
        /// 取得所有属性值的字符串，供更新之用
        /// </summary>
        /// <param name="model"></param>
        /// <param name="propertys"></param>
        /// <returns>(val1,val2)</returns>
        public static string GetValueSting(this ReadonlyRepositoryModel model, string[] propertys)
        {
            IEnumerable<PropertyInfo> arr =
                RepositoryReflectionCache.GetPropertyInfos(model.GetType());
            if (null != propertys)
            {
                arr = arr.Where(p => propertys.Contains(p.Name));
            }

            var sb = new StringBuilder();
            sb.Append(" (");
            foreach (PropertyInfo info in arr)
            {
                sb.AppendFormat(" {0},", info.FastGetValue(model).ToSqlValue());
            }
            --sb.Length;

            sb.Append(" ) ");
            return sb.ToString();
        }
    }
}